<?php

namespace App\Http\Controllers;

use App\Http\Requests\AddCartRequest;
use App\Models\CartItem;
use App\Models\ProductSku;
use App\Services\CartServices;
use Illuminate\Http\Request;

class CartController extends Controller
{
    protected $cartService;

    public function  __construct(CartServices $cartService){
        $this->cartService = $cartService;
    }

    public function rules(){
        return [
            "sku_id" => [
                "required", 
                function($attribute,$value,$fail){
                    if(!$sku = ProductSku::find($value)){
                        return $fail("该商品存在");
                    }
                    if(!$sku->product->on_sale){
                        return $fail("该商品未上架");
                    }
                    if ($sku->stock === 0) {
                        return $fail('该商品已售完');
                    }
                    if ($this->input('amount') > 0 && $sku->stock < $this->input('amount')) {
                        return $fail('该商品库存不足');
                    }
                },
                'amount' => ['required', 'integer', 'min:1'],
            ]
        ];
    }

    public function attributes()
    {
        return [
            'amount' => '商品数量'
        ];
    }

    public function messages()
    {
        return [
            'sku_id.required' => '请选择商品'
        ];
    }

    public function add(AddCartRequest $request){
        $skuId = $request->input("sku_id");
        $amount = $request->input("amount");

        // //商品是否存在购物车
        // if($cart = $user -> CartItems()->where("product_sku_id")->first()){
        //     $cart->update([
        //         "amount" => $cart->mount + $amount,
        //     ]);
        // }else{
        //     $cart = new CartItem(['amount' => $amount]);
        //     $cart->user()->associate($user);
        //     $cart->productSku()->associate($skuId);

        //     $cart->save();
        // }
        $this->cartService->add($skuId,$amount);
        
        return [];
    }

    public function index(Request $request){
        //with方法来预加载商品信息
        $cartItems = $this->cartService->get();
        $address = $request->user()->addresses()->orderBy("last_used_at","desc")->get();
        return view("cart.index",['cartItems'=> $cartItems,"addresses" => $address]);
    }

    public function remove(ProductSku $sku,Request $request){
        $this->cartService->remove($sku->id);
        // $request->user()->cartItems()->where("product_sku_id",$sku->id)->delete();
        return [];
    }

}

